<?php

namespace Home\Controller;

use Think\Controller;
use Home\Biz\AdminBiz;
use Home\Biz\StringBiz;
use Home\Biz\CommonBiz;
use Home\Biz\OrderBiz;

class BuyController extends BaseController {
    /**
     *
     */
	public function cart(){
        $this->assign('page_name', '购物车');

        // 参数校验begin
        $share_code = I('share_code');

        if(empty($share_code)){
            //未有推荐码
            redirect(C('UrlConfig.common_error_url').'?type=21');
            return;
        }
        else{
            cookie(C('AdminConfig.share_code_cookie_name'),
                $share_code,
                array('expire'=>C('AdminConfig.share_code_cookie_expire'),
                    'domain'=>C('AdminConfig.share_code_cookie_domain')));
        }
        // 参数校验end


        // 商品sku列表begin
        $lst_sku_en = M('sku', '', 'DB_product')
            ->where("sku_channel IN (5, 13) AND status = 1")
            ->order("priority DESC")
            ->select();

        $lst_can_buy_sku = array();
        foreach($lst_sku_en as $sku_en){
            $add_sku_en = $sku_en;
            $add_sku_en['image']	= C('UriConfig.sku_image_450_pre_url').$sku_en['image'];
            $add_sku_en['full_desc_url']	= C('UriConfig.desc_url_pre_url').$sku_en['desc_url'];
            array_push($lst_can_buy_sku, $add_sku_en);
        }
        $this->assign('lst_can_buy_sku', $lst_can_buy_sku);
        // 商品sku列表end


        // 加载促销信息begin
        $lst_promotion_en   = M('promotion','','DB_product')->where('promotion_channel=5 AND status=1')->select();

        $this->assign('lst_promotion_en', $lst_promotion_en);

        // 加载促销信息end


        $this->display ( "buy/cartNew" );
    }

	
	public function checkout(){
		$this->assign('page_name', '订单结算');
		
		// 参数校验与处理begin
		$share_code = cookie(C('AdminConfig.share_code_cookie_name'));
		if(empty($share_code)){
			//未有推荐码
			redirect(C('UrlConfig.common_error_url').'?type=21');
			return;
		}
		$promoter_info_en	= M('promoterInfo')->where("share_code='%s'", $share_code)->find();
		if(empty($promoter_info_en)){
			//未关联到推荐人
			redirect(C('UrlConfig.common_error_url').'?type=25');
			return;
		}
		$this->assign('user_id', $promoter_info_en['user_id']);
		
 		$lst_sku_str = I('lst_sku');
        if(empty($lst_sku_str)){
            //未有购买商品
            redirect(C('UrlConfig.common_error_url').'?type=22');
            return;
        }

    	$lst_sku_str = I('lst_sku');
        $this->assign('lst_sku', $lst_sku_str);
		
		$address_id = I('address_id');
		$user_address_en = null;
		if(!empty($address_id)){
			$user_address_en = M('userAddress', '', 'DB_trade')->where("address_id='%s'", $address_id)->find();
		}
		$this->assign('user_address_en', $user_address_en);
		// 参数校验与处理end

        $cart_en    =OrderBiz::calcCart($lst_sku_str);
        $lst_sku_en =$cart_en['lst_sku_en'];


		$this->assign('lst_buy_sku',    $cart_en['lst_sku_en']);
		$this->assign('sku_amount',     $cart_en['goods_amount']);
		$this->assign('promotion_amount', $cart_en['promotion_amount']);
		$this->assign('order_amount',   $cart_en['order_amount']);
		$this->assign('all_goods_qty',  $cart_en['goods_qty']);
		// 商品sku列表end
		
		$this->display ( "buy/checkout" );
	}
	
	
	public function orderSuccess(){
		$this->assign('page_name', '去支付');
		$order_id = I('order_id');
		
		if(empty($order_id)){
			redirect(C('UrlConfig.common_error_url').'?type=31');
			return;
		}
		$order_en = M('orderInfo', '', 'DB_trade')->where("order_id='%s'", $order_id)->find();
		if(empty($order_id)){
			redirect(C('UrlConfig.common_error_url').'?type=32');
			return;
		}
		
		$this->assign('order_id', $order_id);
		$this->display ( "buy/order_success" );
	}
	
	/**
	 * 订单支付中转页
	 */
	public function paymentTransfer(){
		$order_id = I('order_id');
		
		//1.参数校验
		if(empty($order_id)){
			redirect(C('UrlConfig.common_error_url').'?type=31');
			return;
		}
		
		$order_en = M('orderInfo', '', 'DB_trade')->where("order_id='%s'", $order_id)->find();
		if(empty($order_id)){
			redirect(C('UrlConfig.common_error_url').'?type=32');
			return;
		}
		if($order_en['payment_status'] == 1){
			redirect(C('UrlConfig.common_error_url').'?type=34?param='.$order_id);
			return;
		}
		
		
		//2.更改订单状态
		M('orderInfo', '', 'DB_trade')->where("order_id='%s'", $order_id)->setField('order_status', 21);
		//3.写入order_status_change_log begin
		$order_status_change_log = array(
				'order_id'		=> $order_id,
				'order_status'	=> 21,
				'order_status_text'	=> '待支付',
				'remark'		=> '',
				'create_user'	=> 'whaleyFZ.buy paymentTransfer',
				'create_date'	=> date("y-m-d H:i:s", time()),
		);
		M('orderStatusChangeLog', '', 'DB_trade')->add($order_status_change_log);
		//写入order_status_change_log end
		
		//4. 更新promoter_order
		$update_promoter_order_en = array(
				'order_status'	=> 21,
		);
		M('promoterOrder')->where("order_id='%s'",$order_id)->save($update_promoter_order_en);
		
		//5.根据不同支付方式，生成支付请求串
		$html_text = '';
		switch($order_en['payment_method']){
			case 21:
				$html_text = OrderBiz::generateAlipayRequestHtml($order_en);
				break;
			default:
				redirect(C('UrlConfig.common_error_url').'?type=32');
				return;
		}
		
		if(empty($html_text)){
			redirect(C('UrlConfig.common_error_url').'?type=33');
			return;
		}
		
		echo $html_text;
	}
	
	
	public function paymentResult(){
		$this->assign('page_name', '支付结果');
		
		$order_id = '';
		$err_msg  = '';
		
		vendor('alipay.alipay_notify');
		//计算得出通知验证结果
		$alipay_config = C('AlipayConfig');
		
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyReturn();
		if($verify_result) {
			//验证成功
			//请在这里加上商户的业务逻辑程序代码
		
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
		
			
			//商户订单号
			$out_trade_no 	= $_GET['out_trade_no'];
			$order_id		= $out_trade_no;
			//支付宝交易号
			$trade_no 		= $_GET['trade_no'];
			//交易状态
			$trade_status 	= $_GET['trade_status'];
		
			$params_text	= CommonBiz::getParamsStr();
			
			//记录所有支付log到在线支付log表
			$onlinePaymentLog = array(
					'order_id'	=> $order_id,
					'trade_no'	=> $trade_no,
					'trade_status'	=> $trade_status,
					'payment_method'=> 21,
					'params_text'	=> $params_text,
					'create_user'	=> 'whaleyFZ.Buy paymentResult',
					'create_date'	=> date("y-m-d H:i:s", time()),
			);
			
			
			if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//如果有做过处理，不执行商户的业务程序
				$onlinePaymentLog['payment_status'] = 1;
				$err_msg = OrderBiz::orderPaymentSuccess($order_id, $_GET, 'whaleyFZ.buy alipayNotify');			
			}
			else {
				$onlinePaymentLog['payment_status'] = 0;
				$err_msg =  "支付异常"."trade_status=".$_GET['trade_status'];
			}
			M('onlinePaymentLog', '', 'DB_trade')->add($onlinePaymentLog);
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
		}
		else {
			//验证失败
			//如要调试，请看alipay_notify.php页面的verifyReturn函数
			$err_msg = "验证失败";
		}
		
		if(empty($err_msg)){
			$this->assign('payment_status', 1);
		}
		else{
			$this->assign('payment_status', 0);
			$this->assign('err_msg', $err_msg);
		}
		$this->assign('order_id', $order_id);
		$this->display ( "buy/payment_result" );
	}
	
	
	public function queryOrder(){
		$this->assign('page_name', '订单查询');
		$order_id = I('order_id');
	
		$this->display ( "buy/query_order" );
	}
	
	
	public function queryOrderDetail(){
		$this->assign('page_name', '订单详情');
		$order_id = I('order_id');
		
		$order_id = I('order_id');
		
		$promoter_order_en = M('promoterOrder')->where("order_id='%s'",$order_id)->find();
		$promoter_order_en['order_revenue_status_text'] = StringBiz::getPromoterOrderRevenueStatusText($promoter_order_en['order_revenue_status']);
		$order_en = M('orderInfo', '', 'DB_trade')->where("order_id='%s'", $order_id)->find();
		$order_en['order_status_text'] = StringBiz::getPromoterOrderStatusText($order_en['order_status']);
		
		
		$lst_order_detail_en = M('orderDetail', '', 'DB_trade')->where("order_id='%s'",$order_id)->select();
		$all_goods_qty = 0;
		foreach($lst_order_detail_en as $index => $order_detail_en){
			$all_goods_qty = $all_goods_qty + $order_detail_en['qty'];
			$lst_order_detail_en[$index]['image'] = $lst_order_detail_en[$index]['image'];
		}
		
		//是否可以支付
		$can_payment = 0;
		//是否可以取消
		$can_cancel = 0;
		
		
		if(in_array($order_en['order_status'], C('OrderConfig.can_payment_order_status_list'))
				&& in_array($order_en['payment_status'], C('OrderConfig.can_payment_payment_status_list'))){
					$can_payment = 1;
		}
		
		if(in_array($order_en['order_status'], C('OrderConfig.can_cancel_order_status_list'))
				&& in_array($order_en['payment_status'], C('OrderConfig.can_cancel_payment_status_list'))){
					$can_cancel = 1;
		}
		$this->assign('can_payment', $can_payment);
		$this->assign('can_cancel', $can_cancel);
		
		$this->assign('all_goods_qty', $all_goods_qty);
		$this->assign('promoter_order_en', $promoter_order_en);
		$this->assign('order_en', $order_en);
		$this->assign('lst_order_detail_en', $lst_order_detail_en);
		
		$this->display ( "buy/query_order_detail" );
	}

    /**
     * 地址列表
     */
	public function addressList(){
        $this->assign('page_name', '地址列表');
       
        $user_id	= I('user_id');
        $lst_user_address	= M('userAddress','','DB_trade')
        	->where("user_id='%s'", $user_id)->select();

        $this->assign('lst_user_address', $lst_user_address);
        $this->assign('lst_sku', I('lst_sku'));
        $this->assign('user_id', $user_id);
        $this->display ( "buy/addressList" );
    }

	
	/**
	 * 新创建地址，并新创建用户
	 */
	public function addAddress(){
		$this->assign('page_name', '新建地址');
		$this->assign('lst_sku', I('lst_sku'));
		$this->assign('user_id', I('user_id'));
		$this->display ( "buy/addAddress" );
	}
	
	/**
	 * 修改地址
	 */
	public function updateAddress(){
		$this->assign('page_name', '新建地址');
		$address_id = I('address_id');
		$user_address_en = null;
		if(!empty($address_id)){
			$user_address_en = M('userAddress', '', 'DB_trade')->where("address_id='%s'",$address_id)->find();
		}
		$this->assign('user_address_en', $user_address_en);
		$this->assign('user_address_en_json', json_encode($user_address_en));
		
		$this->assign('lst_sku', I('lst_sku'));
		$this->display ("buy/updateAddress");
	}
	
	
	public function alipayNotify(){
		
		vendor('alipay.alipay_notify');
		$alipay_config = C('AlipayConfig');
		$alipayNotify = new \AlipayNotify($alipay_config);
		
		$verify_result = $alipayNotify->verifyNotify();
		if($verify_result) {//验证成功
			/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代
		
		
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
		
			//获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
		
			//商户订单号
		
			$out_trade_no 	= $_POST['out_trade_no'];
			$order_id 		= $out_trade_no;
			//支付宝交易号
			$trade_no 		= $_POST['trade_no'];
			//交易状态
			$trade_status 	= $_POST['trade_status'];
		
			$params_text	= CommonBiz::getParamsStr();
				
			//记录所有支付log到在线支付log表
			$onlinePaymentLog = array(
					'order_id'	=> $order_id,
					'trade_no'	=> $trade_no,
					'trade_status'	=> $trade_status,
					'payment_method'=> 21,
					'params_text'	=> $params_text,
					'create_user'	=> 'whaleyFZ.Buy alipayNotify',
					'create_date'	=> date("y-m-d H:i:s", time()),
			);
		
			if($_POST['trade_status'] == 'TRADE_FINISHED') {
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
				//如果有做过处理，不执行商户的业务程序
		
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
		
				$onlinePaymentLog['payment_status'] = 1;
				$err_msg = OrderBiz::orderPaymentSuccess($order_id, $_POST, 'whaleyFZ.buy alipayNotify');
			}
			else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
				//如果有做过处理，不执行商户的业务程序
		
				//注意：
				//付款完成后，支付宝系统发送该交易状态通知
		
				$onlinePaymentLog['payment_status'] = 1;
				$err_msg = OrderBiz::orderPaymentSuccess($order_id, $_POST, 'whaleyFZ.buy alipayNotify');
			}
		
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
		
			
			M('onlinePaymentLog', '', 'DB_trade')->add($onlinePaymentLog);
			if(empty($err_msg)){
				echo "success";
			}
			else{
				echo "fail";
			}
			//echo "success";		//请不要修改或删除
		}
		else {
			//验证失败
			echo "fail";		
		}
	}
}